<template>
  <div class="risk-assessment">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input
            v-model="searchForm.idCard"
            placeholder="请输入身份证号"
            clearable
          />
        </el-form-item>
        <el-form-item label="评估状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="待评估" value="pending" />
            <el-option label="已评估" value="assessed" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAssess">新增评估</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 评估列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="idCard" label="身份证号" width="180" />
        <el-table-column prop="totalScore" label="总评分" width="100">
          <template #default="scope">
            <el-tag :type="getScoreType(scope.row.totalScore)">
              {{ scope.row.totalScore }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="riskLevel" label="风险等级" width="100">
          <template #default="scope">
            <el-tag :type="getRiskLevelType(scope.row.riskLevel)">
              {{ getRiskLevelText(scope.row.riskLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="suggestion" label="评估建议" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assessor" label="评估人" width="120" />
        <el-table-column prop="createTime" label="评估时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              link
              type="success"
              @click="handleAssess(scope.row)"
            >
              评估
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 评估弹窗 -->
    <el-dialog
      v-model="assessVisible"
      :title="currentAssessment.id ? '风险评估' : '新增评估'"
      width="800px"
      destroy-on-close
    >
      <el-form
        ref="assessFormRef"
        :model="assessForm"
        :rules="assessRules"
        label-width="120px"
      >
        <el-divider content-position="left">基本信息评分</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="ageScore">
              <el-input-number
                v-model="assessForm.ageScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="婚姻状况" prop="marriageScore">
              <el-input-number
                v-model="assessForm.marriageScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教育程度" prop="educationScore">
              <el-input-number
                v-model="assessForm.educationScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="居住状况" prop="residenceScore">
              <el-input-number
                v-model="assessForm.residenceScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">收入情况评分</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月收入" prop="incomeScore">
              <el-input-number
                v-model="assessForm.incomeScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作年限" prop="workYearsScore">
              <el-input-number
                v-model="assessForm.workYearsScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业稳定性" prop="jobStabilityScore">
              <el-input-number
                v-model="assessForm.jobStabilityScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他收入" prop="otherIncomeScore">
              <el-input-number
                v-model="assessForm.otherIncomeScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">信用记录评分</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="信用卡记录" prop="creditCardScore">
              <el-input-number
                v-model="assessForm.creditCardScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款记录" prop="loanHistoryScore">
              <el-input-number
                v-model="assessForm.loanHistoryScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="逾期记录" prop="overdueScore">
              <el-input-number
                v-model="assessForm.overdueScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="征信记录" prop="creditScore">
              <el-input-number
                v-model="assessForm.creditScore"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">评估结果</el-divider>
        <el-form-item label="总评分">
          <el-tag :type="getScoreType(assessForm.totalScore)" size="large">
            {{ assessForm.totalScore }}
          </el-tag>
        </el-form-item>
        <el-form-item label="风险等级">
          <el-tag :type="getRiskLevelType(assessForm.riskLevel)" size="large">
            {{ getRiskLevelText(assessForm.riskLevel) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="评估建议" prop="suggestion">
          <el-input
            v-model="assessForm.suggestion"
            type="textarea"
            :rows="3"
            placeholder="请输入评估建议"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assessVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssessSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="评估详情"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{ detail.customerName }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detail.idCard }}</el-descriptions-item>
        <el-descriptions-item label="总评分">
          <el-tag :type="getScoreType(detail.totalScore)">
            {{ detail.totalScore }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="风险等级">
          <el-tag :type="getRiskLevelType(detail.riskLevel)">
            {{ getRiskLevelText(detail.riskLevel) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="评估建议" :span="2">{{ detail.suggestion }}</el-descriptions-item>
        <el-descriptions-item label="评估人">{{ detail.assessor }}</el-descriptions-item>
        <el-descriptions-item label="评估时间">{{ detail.createTime }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">评分详情</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="年龄评分">{{ detail.ageScore }}</el-descriptions-item>
        <el-descriptions-item label="婚姻状况评分">{{ detail.marriageScore }}</el-descriptions-item>
        <el-descriptions-item label="教育程度评分">{{ detail.educationScore }}</el-descriptions-item>
        <el-descriptions-item label="居住状况评分">{{ detail.residenceScore }}</el-descriptions-item>
        <el-descriptions-item label="月收入评分">{{ detail.incomeScore }}</el-descriptions-item>
        <el-descriptions-item label="工作年限评分">{{ detail.workYearsScore }}</el-descriptions-item>
        <el-descriptions-item label="职业稳定性评分">{{ detail.jobStabilityScore }}</el-descriptions-item>
        <el-descriptions-item label="其他收入评分">{{ detail.otherIncomeScore }}</el-descriptions-item>
        <el-descriptions-item label="信用卡记录评分">{{ detail.creditCardScore }}</el-descriptions-item>
        <el-descriptions-item label="贷款记录评分">{{ detail.loanHistoryScore }}</el-descriptions-item>
        <el-descriptions-item label="逾期记录评分">{{ detail.overdueScore }}</el-descriptions-item>
        <el-descriptions-item label="征信记录评分">{{ detail.creditScore }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  customerName: '',
  idCard: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const tableData = ref([
  {
    customerName: '张三',
    idCard: '440300199001011234',
    totalScore: 85,
    riskLevel: 'low',
    suggestion: '建议通过，风险较低',
    status: 'assessed',
    assessor: '李四',
    createTime: '2024-03-01 10:00:00',
    ageScore: 80,
    marriageScore: 90,
    educationScore: 85,
    residenceScore: 75,
    incomeScore: 90,
    workYearsScore: 85,
    jobStabilityScore: 80,
    otherIncomeScore: 70,
    creditCardScore: 95,
    loanHistoryScore: 90,
    overdueScore: 100,
    creditScore: 85
  }
])

// 评估数据
const assessVisible = ref(false)
const assessFormRef = ref(null)
const currentAssessment = ref({})
const assessForm = reactive({
  ageScore: 0,
  marriageScore: 0,
  educationScore: 0,
  residenceScore: 0,
  incomeScore: 0,
  workYearsScore: 0,
  jobStabilityScore: 0,
  otherIncomeScore: 0,
  creditCardScore: 0,
  loanHistoryScore: 0,
  overdueScore: 0,
  creditScore: 0,
  suggestion: ''
})

// 计算总评分
const totalScore = computed(() => {
  const scores = [
    assessForm.ageScore,
    assessForm.marriageScore,
    assessForm.educationScore,
    assessForm.residenceScore,
    assessForm.incomeScore,
    assessForm.workYearsScore,
    assessForm.jobStabilityScore,
    assessForm.otherIncomeScore,
    assessForm.creditCardScore,
    assessForm.loanHistoryScore,
    assessForm.overdueScore,
    assessForm.creditScore
  ]
  const total = scores.reduce((sum, score) => sum + score, 0)
  return Math.round(total / scores.length)
})

// 计算风险等级
const riskLevel = computed(() => {
  const score = totalScore.value
  if (score >= 90) return 'low'
  if (score >= 70) return 'medium'
  return 'high'
})

// 表单验证规则
const assessRules = {
  suggestion: [
    { required: true, message: '请输入评估建议', trigger: 'blur' }
  ]
}

// 详情数据
const detailVisible = ref(false)
const detail = ref({})

// 查询
const handleSearch = () => {
  loading.value = true
  // TODO: 实现查询逻辑
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 重置
const handleReset = () => {
  searchForm.customerName = ''
  searchForm.idCard = ''
  searchForm.status = ''
  handleSearch()
}

// 评估
const handleAssess = (row) => {
  currentAssessment.value = row || {}
  if (row) {
    Object.assign(assessForm, row)
  } else {
    Object.keys(assessForm).forEach(key => {
      assessForm[key] = key === 'suggestion' ? '' : 0
    })
  }
  assessVisible.value = true
}

// 提交评估
const handleAssessSubmit = async () => {
  if (!assessFormRef.value) return
  
  await assessFormRef.value.validate((valid, fields) => {
    if (valid) {
      const data = {
        ...assessForm,
        totalScore: totalScore.value,
        riskLevel: riskLevel.value
      }
      // TODO: 实现评估提交逻辑
      ElMessage.success('评估提交成功')
      assessVisible.value = false
      handleSearch()
    }
  })
}

// 详情
const handleDetail = (row) => {
  detail.value = row
  detailVisible.value = true
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 获取评分标签类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 70) return 'warning'
  return 'danger'
}

// 获取风险等级标签类型
const getRiskLevelType = (level) => {
  const map = {
    low: 'success',
    medium: 'warning',
    high: 'danger'
  }
  return map[level]
}

// 获取风险等级文本
const getRiskLevelText = (level) => {
  const map = {
    low: '低风险',
    medium: '中风险',
    high: '高风险'
  }
  return map[level]
}

// 获取状态标签类型
const getStatusType = (status) => {
  const map = {
    pending: 'info',
    assessed: 'success',
    rejected: 'danger'
  }
  return map[status]
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    pending: '待评估',
    assessed: '已评估',
    rejected: '已拒绝'
  }
  return map[status]
}
</script>

<style scoped>
.risk-assessment {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
}
</style> 